package com.ddz.service;

import com.ddz.model.User;
import com.ddz.model.enums.PokerType;
import com.ddz.util.JDBCUtil;
import com.ddz.util.PokerUtil;
import com.ddz.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.websocket.Session;
import java.util.List;

public class GameMsgService {

    // 错误消息
    public static void error(String msg, Session session) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", "error");
            jsonObject.put("msg", msg);
            session.getBasicRemote().sendText(msg);
        } catch (Exception e) {
            System.out.println("处理错误请求时出差！");
            e.printStackTrace();
        }

    }

    // 处理客户发来的消息
    public static void handleMessage(String message, String roomId) {
        System.out.println(message);
        if (!StringUtil.isEmpty(message)) {
            JSONObject jsonObject = new JSONObject(message);
            // 处理客户端发来的消息
            if (jsonObject.getString("type").equals("usermsg")) {

                boolean flag = true;
                String msg = "";

                // 判断房间是否满员
                if (GameRoomManager.Room_getinfo(roomId, "Status").equals("waiting")) {
                    flag = false;
                    msg = "人员未满！游戏还未开始！";
                }
                if (flag) {
                    GameRoomManager.broadcastMessage(roomId, message);
                }
                // 发送错误提示信息
                else {
                    JSONObject jsonObject_alert = new JSONObject();
                    jsonObject_alert.put("type", "alert");
                    jsonObject_alert.put("message", msg);
                    jsonObject_alert.put("action", "");
                    GameRoomManager.sendMessageToPlayer(roomId, jsonObject.getString("sender"), jsonObject_alert.toString());
                }
            }
            // 处理抢地主操作
            else if (jsonObject.getString("type").equals("ROB_MASTER")) {

                boolean flag = true;
                String msg = "";

                // 判断游戏是否开始
                if (GameRoomManager.Room_getinfo(roomId, "Status").equals("started")) {
                    flag = false;
                    msg = "地主已被抢！游戏已经开始！";
                }
                // 判断房间是否满员
                else if (GameRoomManager.Room_getinfo(roomId, "Status").equals("waiting")) {
                    flag = false;
                    msg = "人员未满！游戏还未开始！";
                }

                if (flag) {
                    // 设置房间状态为开始
                    GameRoomManager.Room_setinfo(roomId, "Status", "started");
                    GameRoomManager.Room_setcurrent_user(roomId, jsonObject.getString("sender"));
                    // 为玩家添加地主牌
                    GameRoomManager.Room_addloadPokers(roomId, jsonObject.getString("sender"));
                    // 发送玩家手牌
                    JSONObject jsonObject_rob = new JSONObject();
                    jsonObject_rob.put("type", "ROB_MASTER");
                    jsonObject_rob.put("pokerlist", GameRoomManager.Room_userPokers(roomId, jsonObject.getString("sender")));

                    GameRoomManager.sendMessageToPlayer(roomId, jsonObject.getString("sender"), jsonObject_rob.toString());

                    // 更新
                    JSONObject jsonObject_update = new JSONObject();
                    jsonObject_update.put("type", "update");
                    jsonObject_update.put("update", update(roomId));
                    jsonObject_update.put("setimg_landlord", jsonObject.getString("sender"));
                    jsonObject_update.put("music", "rob");
                    GameRoomManager.broadcastMessage(roomId, jsonObject_update.toString());

                    // 广播发送 抢地主 消息
                    JSONObject jsonObject_pass = new JSONObject();
                    jsonObject_pass.put("type", "usermsg");
                    jsonObject_pass.put("sender", jsonObject.getString("sender"));
                    jsonObject_pass.put("content", "抢地主");

                    GameRoomManager.broadcastMessage(roomId, jsonObject_pass.toString());
//                    // 更新
//                    update(roomId);
                }
                // 发送错误提示信息
                else {
                    JSONObject jsonObject_alert = new JSONObject();
                    jsonObject_alert.put("type", "alert");
                    jsonObject_alert.put("message", msg);
                    jsonObject_alert.put("action", "hind");
                    GameRoomManager.sendMessageToPlayer(roomId, jsonObject.getString("sender"), jsonObject_alert.toString());
                }
            }
            // 处理跳过操作
            else if (jsonObject.getString("type").equals("PASS")) {

                boolean flag = true;
                String msg = "";

                // 判断房间是否满员
                if (GameRoomManager.Room_getinfo(roomId, "Status").equals("waiting")) {
                    flag = false;
                    msg = "人员未满！游戏还未开始！";
                }
                // 判断游戏是否开始
                if (!GameRoomManager.Room_getinfo(roomId, "Status").equals("started")) {
                    flag = false;
                    msg = "游戏还未开始！请先抢地主！";
                }
                // 判断是否为当前玩家回合
                else if (!GameRoomManager.Room_judge_current(roomId, jsonObject.getString("sender"))) {
                    flag = false;
                    msg = "还未轮到你出牌！";
                }
                // 判断当前是否必须出牌
                else if (GameRoomManager.Room_getpassnum(roomId) == 2) {
                    flag = false;
                    msg = "当前必须出牌！";
                }
                if (flag) {
                    // 跳过数量加1
                    GameRoomManager.Room_passadd(roomId);
                    // 设置下一位出牌的人
                    GameRoomManager.Room_next_user(roomId);
                    // 清空出牌堆
                    if (GameRoomManager.Room_getpassnum(roomId) == 2) {
                        GameRoomManager.Room_setinfo(roomId, "PokerType", PokerType.NONE.toString());
                        GameRoomManager.Room_setinfo(roomId, "lastpoker", "[]");

                        // 清空中间牌堆
                        JSONObject jsonObject_clear = new JSONObject();
                        jsonObject_clear.put("type", "clear_center");
//                        jsonObject_clear.put("sender", jsonObject.getString("sender"));
                        GameRoomManager.broadcastMessage(roomId, jsonObject_clear.toString());
                    }
                    // 广播发送 要不起 消息
                    JSONObject jsonObject_pass = new JSONObject();
                    jsonObject_pass.put("type", "usermsg");
                    jsonObject_pass.put("sender", jsonObject.getString("sender"));
                    jsonObject_pass.put("content", "要不起");

                    GameRoomManager.broadcastMessage(roomId, jsonObject_pass.toString());

                    // 更新
                    JSONObject jsonObject_update = new JSONObject();
                    jsonObject_update.put("type", "update");
                    jsonObject_update.put("update", update(roomId));
                    jsonObject_update.put("music", "pass");
                    GameRoomManager.broadcastMessage(roomId, jsonObject_update.toString());
//                    // 更新
//                    update(roomId);
                }
                // 发送错误提示信息
                else {
                    JSONObject jsonObject_alert = new JSONObject();
                    jsonObject_alert.put("type", "alert");
                    jsonObject_alert.put("message", msg);
                    jsonObject_alert.put("action", "");
                    GameRoomManager.sendMessageToPlayer(roomId, jsonObject.getString("sender"), jsonObject_alert.toString());
                }
            }

            // 处理玩家出牌操作
            else if (jsonObject.getString("type").equals("hand_poker")) {
                JSONArray jsonArray = jsonObject.getJSONArray("pokerlist");
                System.out.println("hand：" + jsonArray.toString());

                boolean flag = true;
                String msg = "";
                String pokerType_last = GameRoomManager.Room_getinfo(roomId, "PokerType");
                JSONArray jsonArray_lastpoker = new JSONArray(GameRoomManager.Room_getinfo(roomId, "lastpoker"));
                System.out.println(jsonArray_lastpoker.toString());
                System.out.println(jsonArray_lastpoker.length());

                // 判断游戏是否开始
                if (!GameRoomManager.Room_getinfo(roomId, "Status").equals("started")) {
                    flag = false;
                    msg = "游戏还未开始！请先抢地主！";
                }
                // 判断是否为当前玩家回合
                else if (!GameRoomManager.Room_judge_current(roomId, jsonObject.getString("sender"))) {
                    flag = false;
                    msg = "还未轮到你出牌！";
                }
                // 判断出牌是否合法
                else if (!PokerUtil.checkHandPokers(PokerUtil.JsonArrayTolistPoker(jsonArray))) {
                    flag = false;
                    msg = "出牌不符合规则！";
                }

                // 比较牌的大小
                else if (jsonArray_lastpoker.length() != 0 &&
                        !PokerUtil.comparePokerValue(
                                PokerUtil.getHandPokerValueList(PokerUtil.JsonArrayTolistPoker(jsonArray)),
                                PokerUtil.getHandPokerValueList(PokerUtil.JsonArrayTolistPoker(jsonArray_lastpoker)),
                                PokerUtil.getPokerType(PokerUtil.JsonArrayTolistPoker(jsonArray)),
                                PokerType.valueOf(pokerType_last)
                        )) {
                    flag = false;
                    msg = "出牌不符合规则！";
                }

                // 可以符合条件，更新牌堆，设置下一位玩家出牌
                if (flag) {
                    GameRoomManager.Room_setinfo(roomId, "lastpoker", jsonArray.toString());
                    GameRoomManager.Room_setinfo(roomId, "PokerType", PokerUtil.getPokerType(PokerUtil.JsonArrayTolistPoker(jsonArray)).toString());
                    // 归零跳过数量
                    GameRoomManager.Room_clear_passnum(roomId);
                    GameRoomManager.Room_next_user(roomId);

                    // 删除玩家牌
                    GameRoomManager.Room_delPokers(roomId, jsonObject.getString("sender"), PokerUtil.JsonArrayTolistPoker(jsonArray));

                    // 玩家剩余手牌信息
                    JSONArray jsonObject_retainpokers;
                    jsonObject_retainpokers = GameRoomManager.Room_userPokers(roomId, jsonObject.getString("sender"));
                    jsonObject.put("retainpokers", jsonObject_retainpokers);

                    // 给对应玩家发送手牌信息
                    GameRoomManager.sendMessageToPlayer(roomId, jsonObject.getString("sender"), jsonObject.toString());

                    // 更新
                    JSONObject jsonObject_update = new JSONObject();
                    jsonObject_update.put("type", "update");
                    jsonObject_update.put("update", update(roomId));
                    jsonObject_update.put("center_pokers", jsonObject.getJSONArray("pokerlist"));
                    GameRoomManager.broadcastMessage(roomId, jsonObject_update.toString());

                    if (GameRoomManager.Room_getpassnum(roomId) == 2) {
                        GameRoomManager.Room_passadd(roomId);
                    }

                    // 如果玩家手牌为0就结束游戏
                    if (jsonObject_retainpokers.length() == 0) {
                        jsonObject.put("type", "Game_Over");
                        JSONArray win_user = new JSONArray();
                        // 地主获胜
                        if (GameRoomManager.Room_getinfo(roomId, "landlord").equals(jsonObject.getString("sender"))) {
                            win_user.put(GameRoomManager.getPlayerInRoom(roomId, jsonObject.getString("sender")).getNickname());
                            String sql = "UPDATE user SET score = score + 25 WHERE userId = ?;";
                            JDBCUtil.executeUpdate(sql, jsonObject.getString("sender"));
                            for (User user : GameRoomManager.getAllPlayersInRoom(roomId)) {
                                if (!GameRoomManager.Room_getinfo(roomId, "landlord").equals(user.getUserId())) {
                                    sql = "UPDATE user SET score = score - 10 WHERE userId = ?;";
                                    JDBCUtil.executeUpdate(sql, user.getUserId());
                                }
                            }
                        }
                        // 农民获胜
                        else {
                            for (User user : GameRoomManager.getAllPlayersInRoom(roomId)) {
                                if (!GameRoomManager.Room_getinfo(roomId, "landlord").equals(user.getUserId())) {
                                    String sql = "UPDATE user SET score = score + 10 WHERE userId = ?;";
                                    JDBCUtil.executeUpdate(sql, user.getUserId());
                                    win_user.put(user.getNickname());
                                } else {
                                    String sql = "UPDATE user SET score = score - 20 WHERE userId = ?;";
                                    JDBCUtil.executeUpdate(sql, jsonObject.getString("sender"));
                                }
                            }
                        }

                        jsonObject.put("win_users", win_user);

                        GameRoomManager.broadcastMessage(roomId, jsonObject.toString());
                    }
                }
                // 发送错误提示信息
                else {
                    JSONObject jsonObject_alert = new JSONObject();
                    jsonObject_alert.put("type", "alert");
                    jsonObject_alert.put("message", msg);
                    jsonObject_alert.put("action", "");
                    GameRoomManager.sendMessageToPlayer(roomId, jsonObject.getString("sender"), jsonObject_alert.toString());
                }

            }
        }
    }

    // 更新类型消息
    public static JSONObject update(String roomId) {
        try {
            // 建立JSON消息
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            // 获取房间中的玩家列表
            List<User> ls = GameRoomManager.getAllPlayersInRoom(roomId);
            System.out.println(ls);
            for (User user : ls) {
                JSONObject jsonObject_user = new JSONObject();
                jsonObject_user.put("order", user.getOrder());
                jsonObject_user.put("handnum", GameRoomManager.Room_userPokers(roomId, user.getUserId()).length());
                jsonArray.put(jsonObject_user);
            }
            jsonObject.put("players_handnum", jsonArray);
            jsonObject.put("current", GameRoomManager.Room_getcurrent_user(roomId));
            return jsonObject;
        } catch (Exception e) {
            System.out.println("更新异常");
            System.out.println(e.getMessage());
            return null;
        }
    }

    // 游戏开始时同步玩家信息
    public static void startMessage(String roomId) {
        // 建立JSON消息
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        jsonObject.put("type", "userinfo");
        // 获取房间中的玩家列表
        List<User> ls = GameRoomManager.getAllPlayersInRoom(roomId);
        for (User user : ls) {
            jsonArray.put(new JSONObject(user.tojson()));
        }
        jsonObject.put("players", jsonArray);
        // 广播所有玩家的信息
        GameRoomManager.broadcastMessage(roomId, jsonObject.toString());

        // 指定房间进行发牌
        GameRoomManager.Room_dealPokers(roomId);
        // 更改房间状态
        GameRoomManager.Room_setinfo(roomId, "Status", "full");
        // 向对应玩家发送他们的手牌信息
        for (User user : ls) {
            JSONObject json_poker = new JSONObject();
            json_poker.put("type", "poker");
            json_poker.put("pokerlist", GameRoomManager.Room_userPokers(roomId, user.getUserId()));
            GameRoomManager.sendMessageToPlayer(roomId, user.getUserId(), json_poker.toString());
        }

        // 发送地主牌
        JSONObject json_loadPokers = new JSONObject();
        json_loadPokers.put("type", "loadPokers");
        json_loadPokers.put("pokerlist", GameRoomManager.Room_userPokers(roomId, "loadPokers"));
        GameRoomManager.broadcastMessage(roomId, json_loadPokers.toString());
    }

}
